package com.yihu.cms.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.cms.util.Osslog;
import com.yihu.web.bean.Behavior;
import com.yihu.web.bean.UserBehavior;
import com.yihu.web.bean.user.User;
import com.yihu.web.constats.DSConstants;
import com.yihu.web.utils.InfoHelp;
import com.yihu.web.utils.PropertiesUtil;
import com.yihu.yihuds.service.YihuUserService;

public class UserBehaviorFilter implements Filter {
	YihuUserService service = new YihuUserService();

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		String a = request.getParameter("stat");
		String module = request.getParameter("type");
		
		String unlogin = request.getParameter("unlogin");
		Osslog.debug("cms do filter type: " + module+" unlogincode: "+unlogin);
		long uid = 0;
		if (StringUtils.isBlank(a)) {
			Osslog.debug("cms not recording user behavior");
		} else {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			User user = new User();
			if(!StringUtils.isBlank(unlogin)){
				user.setNickName(unlogin);
			}
			try {
				Cookie[] cookies = httpRequest.getCookies();
				for (Cookie c : cookies) {
					String name = c.getName();
					/*Osslog.debug("cookie.name: " + name);
					if ("userId".equals(name)) {
						userId = c.getValue();
						Osslog.debug("cookie.userId: " + userId);
						break;
					}*/
					if ("wxuser".equals(name)) {
						// logger.debug("cookie.userId: "+c.getValue());
						String userJson = InfoHelp.unescape(c.getValue());
						Osslog.debug("cookie.userJson: " + userJson);
						user = JSON.parseObject(userJson, User.class);
						break;
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			Enumeration enu = request.getParameterNames();
			Map<String, Object> parameters = new HashMap();
			while (enu.hasMoreElements()) {
				String paraName = (String) enu.nextElement();
				String value = request.getParameter(paraName);
				if (!paraName.equals("stat"))
					parameters.put(paraName, value);
			}
			String currentURL = httpRequest.getRequestURI();
			// 取得根目录所对应的绝对路径:
			String targetURL = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());
			Osslog.debug("targetURL: " + targetURL);
			Behavior b = null;
			if (module.equals(DSConstants.STAT_PRODUCTDETIAL)) {
				String pid = targetURL.substring(targetURL.lastIndexOf("/") + 1);
				Osslog.debug(module+".pid: " + pid);
				parameters.put("pid", pid);
				b = new Behavior();
				b.setPid(pid);
			}
			else if(module.equals(DSConstants.STAT_ARTICLEDETAIL)||module.equals(DSConstants.STAT_GROUPBUYDETAIL)){
				String pid = targetURL.substring(targetURL.lastIndexOf("/") + 1);
				parameters.put("pid", pid);
				Osslog.debug(module+".pid: " + pid);
				b = new Behavior();
				b.setPid(pid);
			}
			
			Osslog.debug("parameters: " + parameters);
			UserBehavior ub = new UserBehavior();
			ub.setModule(module);
			ub.setParameters(parameters);
			ub.setUser(user);
			if(null!=b){
				ub.setBehavior(b);
			}
			service.addUserBehavior(ub);
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		/*
		 * System.out.println("该url正在过滤。。。。。");
		 *//**
			 * * 1,doFilter的第一个参数为ServletRequest对象。此对象给过滤器提供了对进入的信息（包括 *
			 * 表单数据、cookie和HTTP请求头）的完全访问。 第二个参数为ServletResponse，通常在简单的过 *
			 * 滤器中忽略此参数。最后一个参数为FilterChain，此参数用来调用servlet或JSP页。
			 */
		/*
		 * HttpServletRequest request = (HttpServletRequest) servletRequest;
		 *//**
			 * * 如果处理HTTP请求，并且需要访问诸如getHeader或getCookies等在ServletRequest中 *
			 * 无法得到的方法，就要把此request对象构造成HttpServletRequest
			 *//*
			 * HttpServletResponse response = (HttpServletResponse)
			 * servletResponse; String currentURL = request.getRequestURI();
			 */
		// 取得根目录所对应的绝对路径: String targetURL =
		// currentURL.substring(currentURL.indexOf("/", 1),
		// currentURL.length()); // 截取到当前文件名用于比较 HttpSession session =
		// request.getSession(false); if (!"/login.jsp".equals(targetURL)) {
		// if(!"/userLogin.action".equals(targetURL)){//不过滤登入的action //
		// 判断当前页是否是重定向以后的登录页面页面，如果是就不做session的判断，防止出现死循环 if (session == null ||
		// session.getAttribute("Competence") == null) { // *用户登录以后需手动添加session
		// System.out.println("request.getContextPath()=" +
		// request.getContextPath());
		// response.sendRedirect(request.getContextPath() + "/login.jsp"); //
		// 如果session为空表示用户没有登录就重定向到login.jsp页面 return; } } } // 加入filter链继续向下执行
		// filterChain.doFilter(request, response); /** *
		// 调用FilterChain对象的doFilter方法。Filter接口的doFilter方法取一个FilterChain对象作 为它 *
		// 的一个参数。在调用此对象的doFilter方法时，激活下一个相关的过滤器。如果没有另 *
		// 一个过滤器与servlet或JSP页面关联，则servlet或JSP页面被激活。 */ }}

	}
}
